<template>
  <div class="upload-container">
    <!-- 文件选择按钮 -->
    <el-upload
      action=""
      :auto-upload="false"
      :on-change="handleFileChange"
      :show-file-list="false"
      class="upload-demo"
    >
      <el-button type="primary" size="mini" icon="el-icon-upload2">{{buttonName}}</el-button>
    </el-upload>
<!--    -->
    <!--    显示图片-->
    <div class="slot" >
      <el-table :data="newFileList"  style="width:100%">
        <el-table-column prop="fileName" label="名称"></el-table-column>
        <el-table-column prop="ext" label="类型"></el-table-column>
        <el-table-column prop="size" label="大小"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="previewImage(scope.row)">预览</el-button>
            <el-button type="primary" size="mini" @click="downloadFile(scope.row)">下载</el-button>
            <el-button type="danger" size="mini" @click="deleteFile(scope)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 弹窗：上传进度 -->
    <el-dialog title="文件上传中" :visible.sync="uploading" width="400px" :close-on-click-modal="false" :show-close="false">
      <el-progress :percentage="progress" :status="statusName"></el-progress>
    </el-dialog>

<!--    文件预览-->
  <previewPicture ref="dialogs"></previewPicture>
  </div>
</template>

<script>
import axios from "axios";
import {delFinanceHzd}  from "@/apilist/Finance";
import previewPicture from "./previewPicture";

export default {
  data() {
    return {
      fileList: [], // 存储选中的文件
      uploading: false, // 是否正在上传（控制弹窗）
      progress: 0, // 上传进度
      statusName: "warning",
    };
  },
  props:["dir","files","btn-name","file-name"],
  components: {previewPicture},
  computed:{
      newFileList(){
        if(Array.isArray(this.files) && this.files.length > 0){
          const arr =  this.fileList.concat(this.files);
          return this.mergeByKeys(arr,["fileName"],(existing, current) => {
            existing.count += current.count; // 定义数值合并规则
          });
        }
        return this.fileList;
      },
      buttonName() {
        if(!this.fun.isNull(this.btnName)) return this.btnName;
        return "附件";
      },


  },
  methods: {
    // 选择文件
    handleFileChange(file) {
       try {
         this.newFileList.forEach(v => {
           if (v.fileName == file.name) {
             throw new Error(`文件${file.name}重复,请检查`);
           }
         })
         this.uploadFiles(file);
       }catch (e){
         this.$message.error(e.message);
       }
    },

    // 上传文件
    async uploadFiles(file) {
      this.progress = 0; // 重置进度
      const formData = new FormData();
      formData.append("file",file.raw)
      formData.append("dir",this.dir)
      const uploadURL = process.env.NODE_ENV === "production" ? process.env.UPLOAD_URL : "/oa/uploadFiles";
      try {
        await axios.post(uploadURL, formData, {
          onUploadProgress: progress => {
            this.uploading = true; // 显示弹窗
            // 计算上传进度（保留两位小数）
            this.progress = Number(
              ((progress.loaded / progress.total) * 100).toFixed(2)
            );
            if(this.progress == 100) this.statusName = "success";
          },
        }).then(res => {
          this.$message({
            type:"success",
            message: "上传成功",
            onClose:()=>{
              this.newFileList.push(res.data.data);
            }
          });
        });

      } catch (error) {
        this.$message.error('上传失败');
      } finally {
        this.uploading = false;
        this.progress = 0; // 重置进度
      }
    },


    //预览图片
    previewImage(img){
      let ext = img.ext
      if(ext == 'doc' || ext == 'docx' || ext == 'ppt' || ext == 'pptx' || ext == 'xls' || ext == 'xlsx'){
        this.fun.previewOffice(img.fileUrl)
      }else{
        this.$refs.dialogs.visable=true
        this.$refs.dialogs.img_path = img.fileUrl
      }

    },
    //下载图片
    downloadFile(file){
      let url = file.fileUrl
      let fileName = file.fileName
      this.fun.downloadFile(url,fileName)
    },

    //删除
    deleteFile(col){
      let index = col.$index;
      let file = col.row;
      console.log(col)
      if(file.hasOwnProperty("id") && file.id){
        delFinanceHzd({id: file.id}).then(res => {
            this.$message({
              type:"success",
              message: "删除成功",
              onClose:()=>{
                this.newFileList.splice(index,1);
                //this.$emit("deleteFile",index);
              }
            });
        });
      }else{
        this.newFileList.splice(index,1);
        //this.$emit("deleteFile",index);
      }
    },
    //数组合并去重
    mergeByKeys(array, keys, mergeStrategy) {
      return array.reduce((acc, current) => {
        // 生成复合 Key（如 type-remark）
        const compositeKey = keys.map(k => current[k]).join('-');
        const existing = acc.find(item =>
          keys.every(k => item[k] === current[k])
        );

        if (existing) {
          mergeStrategy(existing, current); // 自定义合并逻辑
        } else {
          acc.push({ ...current });
        }
        return acc;
      }, []);
    },
    //获取上传的文件列表
    getNewFileList(){
      return this.newFileList;
    },
    clsNewFileList(){
      this.newFileList = []
    }

  }
};
</script>

<style scoped>
.upload-container {
  text-align: left;
}
.upload-demo{
  display: inline-block !important;
  width:100% !important;
  text-align: left;
  padding-bottom: 10px;
}
</style>
